package com.Jano.fillter;

/**
 * description: CommitlimitFilter <br>
 * date: 2022/6/11 1:34 PM <br>
 * author: zoumaoji <br>
 * version: 1.0 <br>
 */

import com.Jano.dto.CategoryDto;
import com.Jano.dto.Result;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.Jano.constant.BusinessConstant.*;

/**
 * 提交限制过滤器
 * 在30s某用户的提交操作最多只能进行5次，超过5次提示过于频繁。
 */
public class CommitLimitFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        String userKey = req.getParameter("userId");
        //没有userId就直接放行
        if (StringUtils.isBlank(userKey)) {
            filterChain.doFilter(req, res);
        }else {
            try (JedisPool jedisPool = new JedisPool(REDIS_HOST, REDIS_POST);
                 Jedis jedis = jedisPool.getResource()) {
                if (!jedis.exists(userKey)) {
                    jedis.set(userKey, "1");
                    jedis.expire(userKey, COMMIT_USER_TTL);
                } else {
                    Long commitCount = jedis.incr(userKey);
                    if (commitCount < COMMIT_COUNT_LIMIT) {
                        filterChain.doFilter(req, res);
                    } else {
                        res.setContentType(MEDIA_TYPE_JSON);
                        Result result = new Result();
                        result.setSuccess(false);
                        result.setErrMsg("提交次数过于频繁，请稍后再试");
                        res.getWriter().print(JSON.toJSONString(result));
                    }
                }
            }
        }

    }

    @Override
    public void destroy() {

    }
}
